#ifndef QBYTEARRAYUTIL_H
#define QBYTEARRAYUTIL_H
#include <QByteArray>
#include <QtEndian>

class QByteArrayUtil
{
public:
    static QByteArray fromHex(QByteArrayView);
    static QByteArray toHex(QByteArrayView);

    static QByteArray fromBin(QByteArrayView);
    static QByteArray toBin(QByteArrayView);

    static QByteArray fromOct(QByteArrayView);
    static QByteArray toOct(QByteArrayView);

    template<class ITER_TYPE>
    static QByteArray fromIter(ITER_TYPE first, ITER_TYPE last, qsizetype count, bool bigEndian) {

        QByteArray ba; ba.reserve(count * sizeof(*first));

        if (bigEndian) {
            for (auto iter = first; iter != last; iter++) {
                auto val = qToBigEndian(*iter);
                ba.append((char*)&val, sizeof(val));
            }
        }
        else {
            for (auto iter = first; iter != last; iter++) {
                auto val = qToLittleEndian(*iter);
                ba.append((char*)&val, sizeof(val));
            }
        }

        return ba;
    }


    template<class T>
    static QByteArray fromContainer(T c, bool bigEndian) {
        return fromIter(c.cbegin(), c.cend(), c.size(), bigEndian);
    }

    template<class T>
    static T toContainer(QByteArray ba, bool bigEndian) {
        T c;
        auto elementSize = sizeof(typename T::value_type);
        auto N = ba.size() % elementSize;
        if (N) {
            for (int i = 0; i < elementSize - N; i++)
                ba.push_front(char(0)); // 长度不足，在最前面补0
        }

        if (bigEndian) {
            for (qsizetype i = 0; i < ba.size(); i += elementSize) {
                auto val = *(typename T::value_type*)(ba.data() + i);
                c.append(qToBigEndian(val));
            }
        }
        else {
            for (qsizetype i = 0; i < ba.size(); i += elementSize) {
                auto val = *(typename T::value_type*)(ba.data() + i);
                c.append(qToLittleEndian(val));
            }
        }

        return c;
    }

private:
    QByteArrayUtil() = delete;
};

#endif // QBYTEARRAYUTIL_H
